<template>
    <div class="mqtt-schema-editor">
        <div class="tabs-container">
            <div class="tabs-wrapper">
                <div
                    v-for="tab in typeTabs"
                    :key="tab.key"
                    class="custom-tab"
                    :class="{ active: activeTypeTab === tab.key }"
                    @click="handleTypeTabChange(tab.key)"
                >
                    <a-icon type="file" class="tab-icon" />
                    <span>{{ tab.title }}</span>
                    <a-icon
                        v-if="typeTabs.length > 1 && tab.key !== 'tab-1'"
                        type="close"
                        class="close-icon"
                        @click.stop="removeTypeTab(tab.key)"
                    />
                </div>
                <a-button
                    type="dashed"
                    size="small"
                    icon="plus"
                    class="add-tab-btn"
                    @click="showAddModal = true"
                >
                    添加
                </a-button>
                <a-button
                    type="primary"
                    size="small"
                    class="save-config-btn"
                    @click="handleSaveConfig"
                >
                    保存配置
                </a-button>
            </div>
            <div class="tab-content">
                <div
                    v-for="tab in typeTabs"
                    v-show="activeTypeTab === tab.key"
                    :key="tab.key"
                    class="tab-pane"
                >
                    <div class="inner-tabs">
                        <div class="inner-tabs-header">
                            <a-button
                                :type="activeInnerTab === 'publish' ? 'primary' : 'default'"
                                @click="activeInnerTab = 'publish'"
                            >
                                发布
                            </a-button>
                            <a-button
                                :type="activeInnerTab === 'subscribe' ? 'primary' : 'default'"
                                @click="activeInnerTab = 'subscribe'"
                            >
                                订阅
                            </a-button>
                        </div>
                        <div class="inner-tabs-content">
                            <div v-show="activeInnerTab === 'publish'">
                                <json-schema-editor
                                    :ref="'publish-' + tab.key.replace('tab-', '')"
                                    :schema="tab.publishSchema"
                                    :tab-info="{
                                        name: tab.title,
                                        index: tab.key.replace('tab-', ''),
                                        type: 'pub',
                                    }"
                                    @update:schema="
                                        (val) => updateSchema(tab.key, 'publish', val)
                                    "
                                />
                            </div>
                            <div v-show="activeInnerTab === 'subscribe'">
                                <json-schema-editor
                                    :ref="'subscribe-' + tab.key.replace('tab-', '')"
                                    :schema="tab.subscribeSchema"
                                    :tab-info="{
                                        name: tab.title,
                                        index: tab.key.replace('tab-', ''),
                                        type: 'sub',
                                    }"
                                    @update:schema="
                                        (val) => updateSchema(tab.key, 'subscribe', val)
                                    "
                                />
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <a-modal
            v-model="showAddModal"
            title="添加新标签页"
            @ok="handleAddTab"
            @cancel="resetAddModal"
        >
            <a-form :model="formState" :rules="rules">
                <a-form-item label="标签页名称" name="tabName">
                    <a-input v-model="formState.tabName" placeholder="请输入标签页名称" />
                </a-form-item>
            </a-form>
        </a-modal>
    </div>
</template>

<script>
// EdgeTabManager全局函数已通过统一的TabManager注册，无需额外导入
import { Button, Modal, Form, Input, Icon } from 'ant-design-vue'
import JsonSchemaEditor from './JsonSchemaEditor.vue'

export default {
    name: 'MqttSchemaEditor',
    components: {
        AButton: Button,
        AModal: Modal,
        AForm: Form,
        AFormItem: Form.Item,
        AInput: Input,
        AIcon: Icon,
        JsonSchemaEditor
    },
    data() {
        return {
            typeTabs: [
                {
                    key: 'tab-1',
                    title: '自定义类型',
                    publishSchema: {},
                    subscribeSchema: {}
                }
            ],
            activeTypeTab: 'tab-1',
            activeInnerTab: 'publish',
            showAddModal: false,
            formState: {
                tabName: ''
            },
            rules: {
                tabName: [
                    { required: true, message: '请输入标签页名称', trigger: 'blur' },
                    {
                        min: 1,
                        max: 20,
                        message: '长度在 1 到 20 个字符',
                        trigger: 'blur'
                    }
                ]
            },
            tabCounter: 1
        }
    },
    mounted() {
        this.$nextTick(() => {
            this.loadMqttFormatJsonAll()
        })
    },
    methods: {
        handleTypeTabChange(key) {
            this.activeTypeTab = key
        },
        async removeTypeTab(targetKey) {
            const idx = this.typeTabs.findIndex(tab => tab.key === targetKey)
            if (idx !== -1) {
                const that = this // 保存组件实例引用
                Modal.confirm({
                    title: '确认删除',
                    content: `是否确认删除标签页 "${this.typeTabs[idx].title}"？`,
                    okText: '确认',
                    cancelText: '取消',
                    async onOk() {
                        try {
                            // 需要获取id
                            const id = that.typeTabs[idx].id
                            const res = await that.$tabManager.edge.deleteMqttFormatJson({ id })
                            if (res.code === 0) {
                                // 提示删除成功
                                that.$message.success('删除成功')
                                that.typeTabs.splice(idx, 1)
                                if (that.activeTypeTab === targetKey) {
                                    that.activeTypeTab = that.typeTabs[Math.max(0, idx - 1)].key
                                }
                            } else {
                                // 提示删除失败
                                that.$message.error('删除失败：' + res.msg)
                            }
                        } catch (error) {
                            that.$message.error('删除失败：' + error.message)
                        }
                    },
                    onCancel() {
                        // 用户取消删除，不做任何操作
                    }
                })
            }
        },
        async handleAddTab() {
            if (!this.formState.tabName.trim()) {
                return
            }

            // 需要把publishSchema 和 subscribeSchema 放到extra中
            const extraData = {
                publishSchemaFile: {},
                publishSchemaOriginFile: {},
                subscribeSchemaFile: {},
                subscribeSchemaOriginFile: {}
            }

            const newData = {
                name: this.formState.tabName.trim(),
                id: -1,
                groupDeviceId: -1,
                extra: extraData
            }
            const res = await this.$tabManager.edge.addMqttFormatJson(JSON.stringify(newData))
            if (res.code === 0) {
                // 提示添加成功
                this.$message.success('添加成功')
                console.log('handleAddTab res ' + res.data)
                const extra = JSON.parse(res.data)
                this.tabCounter++
                const newKey = `tab-${this.tabCounter}`
                this.typeTabs.push({
                    key: newKey,
                    title: this.formState.tabName.trim(),
                    extra: extraData,
                    id: extra.id
                })
                this.activeTypeTab = newKey
            } else {
                // 提示添加失败
                this.$message.error('添加失败' + res.msg)
            }
            this.resetAddModal()
        },
        resetAddModal() {
            this.showAddModal = false
            this.formState.tabName = ''
        },
        updateSchema(tabKey, type, schema) {
            const tab = this.typeTabs.find(t => t.key === tabKey)
            if (tab) {
                if (type === 'publish') {
                    tab.publishSchema = schema
                } else {
                    tab.subscribeSchema = schema
                }
            }
        },
        async handleSaveConfig() {
            try {
                // 获取当前tab数据
                const currentTab = this.typeTabs.find(tab => tab.key === this.activeTypeTab)
                const tabIndex = currentTab.key.replace('tab-', '')
                
                // 通过refs获取编辑器实例
                const publishEditor = this.$refs[`publish-${tabIndex}`]
                const subscribeEditor = this.$refs[`subscribe-${tabIndex}`]

                if (!publishEditor || !publishEditor[0] || !subscribeEditor || !subscribeEditor[0]) {
                    throw new Error('编辑器实例未找到')
                }

                const extraData = {
                    publishSchemaFile: publishEditor[0].getJsonFileContent(),
                    publishSchemaOriginFile: publishEditor[0].getJsonOriginFileContent(),
                    subscribeSchemaFile: subscribeEditor[0].getJsonFileContent(),
                    subscribeSchemaOriginFile: subscribeEditor[0].getJsonOriginFileContent()
                }
                // 保存标签页配置
                const config = {
                    id: currentTab.id,
                    name: currentTab.title,
                    groupDeviceId: -1,
                    extra: extraData
                }
                console.log('saveMqttFormatJson ' + JSON.stringify(config))
                const res = await this.$tabManager.edge.saveMqttFormatJson(JSON.stringify(config))
                if (res.code === 0) {
                    // 需要把数据更新到对应tab
                    currentTab.extra = extraData
                    this.$message.success('配置保存成功')
                } else {
                    this.$message.error('配置保存失败：' + res.msg)
                }
            } catch (error) {
                console.error('保存配置失败:', error)
                console.error('Error stack:', error.stack)
                this.$message.error('保存配置失败: ' + (error.message || '未知错误'))
            }
        },
        // 提供给父组件调用的重新加载方法
        reloadData() {
            console.log('🔄 [MqttSchemaEditor] 重新加载数据')
            this.loadMqttFormatJsonAll()
        },

        async loadMqttFormatJsonAll() {
            try {
                // 加载标签页配置
                const res = await this.$tabManager.edge.getMqttFormatJsonAll()
                if (res.code === 0) {
                    const data = JSON.parse(res.data)
                    if (!Array.isArray(data) || data.length === 0) {
                        console.log('No data to load')
                        return
                    }

                    // 处理每个标签页数据
                    this.typeTabs = await Promise.all(data.map(async(tab, index) => {
                        try {
                            // 解析extra字段
                            const extraAll = JSON.parse(tab.extra)
                            const extra = extraAll.extra

                            // 使用索引+1作为key的数字部分
                            const tabIndex = index + 1
                            const extraData = {
                                publishSchemaFile: extra.publishSchemaFile.data || {},
                                publishSchemaOriginFile: extra.publishSchemaOriginFile.data || {},
                                subscribeSchemaFile: extra.subscribeSchemaFile.data || {},
                                subscribeSchemaOriginFile: extra.subscribeSchemaOriginFile.data || {}
                            }

                            // 创建标签页基本结构
                            const tabData = {
                                key: `tab-${tabIndex}`,
                                id: tab.id, // 保留原始id用于数据库操作
                                title: tab.name || '未命名标签页',
                                extra: extraData
                            }
                            return tabData
                        } catch (parseError) {
                            console.error('Error parsing tab data:', parseError, tab)
                            // 返回一个基本的标签页结构，避免整个加载失败
                            const tabIndex = index + 1
                            return {
                                key: `tab-${tabIndex}`,
                                id: tab.id,
                                title: tab.name || '解析错误的标签页',
                                extra: {
                                    publishSchemaFile: {},
                                    publishSchemaOriginFile: {},
                                    subscribeSchemaFile: {},
                                    subscribeSchemaOriginFile: {}
                                }
                            }
                        }
                    }))

                    // 设置活动标签页和计数器
                    if (this.typeTabs.length > 0) {
                        this.activeTypeTab = this.typeTabs[0].key
                        // 使用数组长度作为计数器的初始值
                        this.tabCounter = this.typeTabs.length
                    }

                    // 更新组件引用
                    this.$nextTick(() => {
                        this.typeTabs.forEach(tab => {
                            // 从key中提取索引号
                            const tabIndex = tab.key.replace('tab-', '')
                            const publishEditor = this.$refs[`publish-${tabIndex}`]
                            const subscribeEditor = this.$refs[`subscribe-${tabIndex}`]

                            if (publishEditor && publishEditor[0]) {
                                // publishEditor[0].setJsonContent(tab.publishSchema.jsonFileContent)
                                publishEditor[0].setOriginFileContent(tab.extra.publishSchemaOriginFile)
                            }

                            if (subscribeEditor && subscribeEditor[0]) {
                                // subscribeEditor[0].setJsonContent(tab.subscribeSchema.jsonFileContent)
                                subscribeEditor[0].setOriginFileContent(tab.extra.subscribeSchemaOriginFile)
                            }
                        })
                    })
                }
            } catch (error) {
                console.error('加载配置失败:', error)
                this.$message.error('加载配置失败：' + error.message)
            }
        }
    }
}
</script>

<style scoped>
.mqtt-schema-editor {
    height: 100%;
    width: 100%;
    display: flex;
    flex-direction: column;
    position: relative;
    overflow: hidden; /* 防止内容溢出 */
}
.tabs-container {
    display: flex;
    flex-direction: column;
    width: 100%;
    height: 100%;
    overflow: hidden; /* 防止内容溢出 */
}
.tabs-wrapper {
    display: flex;
    align-items: center;
    border-bottom: 1px solid #f0f0f0;
    padding: 0 16px;
    flex-shrink: 0;
    height: 40px;
    overflow-x: auto;
    overflow-y: hidden;
    white-space: nowrap;
    scrollbar-width: thin;
    position: relative;
}
.tabs-wrapper::-webkit-scrollbar {
    height: 6px;
}
.tabs-wrapper::-webkit-scrollbar-track {
    background: #f1f1f1;
}
.tabs-wrapper::-webkit-scrollbar-thumb {
    background: #888;
    border-radius: 3px;
}
.tabs-wrapper::-webkit-scrollbar-thumb:hover {
    background: #555;
}
.custom-tab {
    display: inline-flex;
    align-items: center;
    padding: 8px 16px;
    margin-right: 2px;
    border: 1px solid #f0f0f0;
    border-bottom: none;
    cursor: pointer;
    background: #fafafa;
    border-radius: 2px 2px 0 0;
    transition: all 0.3s;
    min-width: 120px;
    justify-content: space-between;
    flex-shrink: 0;
}
.custom-tab.active {
    background: #fff;
    border-bottom: 2px solid #1890ff;
    color: #1890ff;
}
.custom-tab:hover {
    color: #1890ff;
}
.tab-icon {
    margin-right: 8px;
    font-size: 14px;
}
.custom-tab span {
    flex: 1;
    text-align: center;
    margin-right: 8px;
}
.close-icon {
    margin-left: auto;
    font-size: 12px;
    color: #999;
}
.close-icon:hover {
    color: #ff4d4f;
}
.add-tab-btn {
    margin-left: 8px;
    flex-shrink: 0;
}
.save-config-btn {
    margin-left: 8px;
    flex-shrink: 0;
}
.tab-content {
    flex: 1;
    padding: 0;
    min-height: 0;
    display: flex;
    flex-direction: column;
    overflow: hidden; /* 防止内容溢出 */
}
.tab-pane {
    height: 100%;
    display: flex;
    flex-direction: column;
    overflow: hidden; /* 防止内容溢出 */
}
.tab-pane :deep(.ant-tabs) {
    height: 100%;
    display: flex;
    flex-direction: column;
}
.tab-pane :deep(.ant-tabs-nav) {
    margin: 0;
    padding: 0 16px;
}
.tab-pane :deep(.ant-tabs-content) {
    flex: 1;
    min-height: 0;
    display: flex;
    flex-direction: column;
}
.tab-pane :deep(.ant-tabs-tabpane) {
    height: 100%;
    padding: 16px;
    display: flex;
    flex-direction: column;
}
.tab-pane :deep(.ant-tabs-tabpane > div) {
    height: 100%;
    display: flex;
    flex-direction: column;
    max-height: calc(100vh - 200px);
    overflow: auto;
}
.inner-tabs {
    display: flex;
    flex-direction: column;
    height: 100%;
}
.inner-tabs-header {
    padding: 8px 16px;
    border-bottom: 1px solid #f0f0f0;
    display: flex;
    gap: 8px;
    flex-shrink: 0; /* 防止被压缩 */
}
.inner-tabs-content {
    flex: 1;
    padding: 16px;
    overflow: auto;
    min-height: 0; /* 防止flex子元素溢出 */
}
</style> 